const app = getApp();

Page({
  data: {
    lastScanResult: "",
    scanCount: 0,
    scanHistory: [],
  },

  onLoad: function () {
    // 从本地存储加载历史记录
    const history = wx.getStorageSync("scanHistory");
    if (history) {
      this.setData({
        scanHistory: history,
        scanCount: history.length,
      });
    }
  },

  onHide: function () {
    // 页面隐藏时自动保存Excel
    // this.autoSaveExcel()
  },

  onUnload: function () {
    // 页面卸载时自动保存Excel
    // this.autoSaveExcel()
  },

  autoSaveExcel: function () {
    if (this.data.scanHistory.length === 0) {
      return;
    }

    this.saveToExcel("auto_save");
  },

  saveToExcel: function (type = "manual") {
    if (this.data.scanHistory.length === 0) {
      wx.showToast({
        title: "暂无数据可导出",
        icon: "none",
      });
      return;
    }

    // 准备Excel数据
    const excelData = this.data.scanHistory.map((item) => [
      item.code,
      item.time,
    ]);
    excelData.unshift(["快递单号", "扫描时间"]); // 添加表头

    // 将数据转换为CSV格式
    const csvContent = excelData.map((row) => row.join(",")).join("\n");

    // 创建临时文件
    const fs = wx.getFileSystemManager();
    const timestamp = new Date().getTime();
    const fileName = `express_codes_${timestamp}.xlsx`;
    const tempFilePath = `${wx.env.USER_DATA_PATH}/${fileName}`;

    try {
      // 先写入临时文件
      fs.writeFileSync(tempFilePath, csvContent, "utf8");

      // 获取下载目录路径
      const downloadPath = `${wx.env.USER_DATA_PATH}/Download`;

      // 确保下载目录存在
      try {
        fs.accessSync(downloadPath);
      } catch (e) {
        fs.mkdirSync(downloadPath, true);
      }

      // 复制文件到下载目录
      const finalPath = `${downloadPath}/${fileName}`;
      fs.copyFileSync(tempFilePath, finalPath);

      // 显示保存位置提示
      wx.showModal({
        title: "文件已保存",
        content: `文件已保存到：\n${finalPath}\n\n您可以在手机的"下载"文件夹中找到它。`,
        showCancel: false,
        success: () => {
          // 打开文档查看器
          wx.openDocument({
            filePath: finalPath,
            fileType: "xlsx",
            success: () => {
              if (type === "manual") {
                wx.showToast({
                  title: "导出成功",
                  icon: "success",
                });
              }
              console.log("文件保存成功");
            },
            fail: (err) => {
              console.error("打开文件失败", err);
              wx.showToast({
                title: "打开文件失败",
                icon: "none",
              });
            },
          });
        },
      });
    } catch (error) {
      console.error("文件保存失败", error);
      wx.showToast({
        title: "文件保存失败",
        icon: "none",
      });
    }
  },

  startScan: function () {
    wx.scanCode({
      onlyFromCamera: true,
      scanType: ["barCode", "qrCode"],
      success: (res) => {
        const result = res.result;
        this.setData({
          lastScanResult: result,
        });

        // 添加到历史记录
        const newHistory = [
          ...this.data.scanHistory,
          {
            code: result,
            time: new Date().toLocaleDateString(),
          },
        ];

        this.setData({
          scanHistory: newHistory,
          scanCount: newHistory.length,
        });

        // 保存到本地存储
        wx.setStorageSync("scanHistory", newHistory);

        // 显示成功提示
        wx.showToast({
          title: "扫描成功",
          icon: "success",
        });
      },
      fail: (res) => {
        wx.showToast({
          title: "扫描失败",
          icon: "none",
        });
      },
    });
  },

  exportToExcel: function () {
    this.saveToExcel("manual");
  },

  clearHistory: function () {
    wx.showModal({
      title: "警告",
      content: "确定要清空所有扫描记录吗？此操作不可恢复！",
      confirmText: "清空",
      confirmColor: "#ff4d4f",
      success: (res) => {
        if (res.confirm) {
          // 清空数据
          this.setData({
            scanHistory: [],
            scanCount: 0,
            lastScanResult: "",
          });
          wx.setStorageSync("scanHistory", []);
          
          wx.showToast({
            title: "已清空",
            icon: "success",
          });
        }
      },
    });
  },
});
